#include <QSqlError>
#include <QSqlQuery>
#include <QSqlQueryModel>
#include <QSqlRecord>
#include <QBuffer>
#include <QTextDocument>

#include "projectbayadapter.h"

///////// ProjectBayAdapter ///////////////////////////////////////////////////////////////////////

ProjectBayAdapter::ProjectBayAdapter()
    : QObject()
{
}

QString ProjectBayAdapter::name() const
{
    return "projectbayadapter";
}

QString ProjectBayAdapter::description() const
{
    return "This plugin provides connection to ARS Project Bay";
}

bool ProjectBayAdapter::connectToDatabase()
{
    m_database = QSqlDatabase::addDatabase("QSQLITE");
    m_database.setDatabaseName("testdata\\db.db");

    if(!m_database.open())
    {
        qDebug(qPrintable(QString("Unable to connect: ") + m_database.lastError().text()));
        return false;
    }

    return true;
}

UseCaseModel * ProjectBayAdapter::createModel()
{
    QSqlQueryModel queryModel;
    queryModel.setQuery("SELECT id, name, description FROM apb_usecase");
    if (queryModel.lastError().isValid())
    {
        qDebug(qPrintable(queryModel.lastError().text()));
        return 0;
    }

    UseCaseModel * model = new UseCaseModel(this);

    for (int i = 0; i < queryModel.rowCount(); ++i)
    {
        UseCase * uc = new UseCase(model);
        QSqlRecord record = queryModel.record(i);

        for(int j = 0; j < record.count(); j++)
            uc->setProperty(record.fieldName(j).toAscii(), record.value(j));

        model->addUseCase(uc);
     }

    return model;
}

bool ProjectBayAdapter::loadUseCase(UseCase * uc)
{
    if(!uc)
        return false;

    QSqlQuery query("SELECT requirements FROM apb_usecase WHERE id = " + uc->id());
    if(!query.exec())
        return false;

    UseCaseBody * body = new UseCaseBody(uc);
    QString htmlString = query.value(0).toString();
    if(htmlString.isEmpty())
    {
        uc->setBody(body);
        return true;
    }

    QTextDocument * reqDoc = new QTextDocument(uc);
    reqDoc->setHtml(htmlString); //! \todo check HTML format
    body->setRequirements(reqDoc);
    uc->setBody(body);

    return true;
}

bool ProjectBayAdapter::saveUseCase(UseCase * uc)
{
    if(!uc || !uc->body())
        return false;

    QSqlQuery query("UPDATE apb_usecase SET "\
                    "name = " + uc->name() + " " +\
                    "description = " + uc->description() + " " +\
                    "requirements = " + uc->body()->requirements()->toHtml() + " " +\
                    "WHERE id = " + QString::number(uc->id()));

    if(!query.exec())
        return false;

    return true;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
